"""
@Author    : ghenyar
@Time      : 2025/8/28 11:09
@File      : __init__.py
@Desc      : 
"""
from .wx import *
from .pay import *

import json
import random
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from base64 import b64decode
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend


def decrypting_phone_number(encryptedData: str, iv: str, sessionKey: str) -> str:
    """
    解密手机号码数据
    :param encryptedData: 加密的手机号码数据
    :param iv: 初始向量
    :param sessionKey: 会话密钥
    :return: 解密后的手机号码数据
    """
    encrypted_data = b64decode(encryptedData)
    session_key = b64decode(sessionKey)
    iv = b64decode(iv)

    # 创建 AES 解密器
    cipher = Cipher(algorithms.AES(session_key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()

    # 解密数据
    decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()

    # 去除填充
    unpadder = padding.PKCS7(128).unpadder()
    decrypted_data = unpadder.update(decrypted_data) + unpadder.finalize()

    # 解析 JSON 数据
    decrypted_data = json.loads(decrypted_data.decode('utf-8'))

    return decrypted_data['phoneNumber']


def random_charts() -> str:
    """
    生成随机字符串
    :return :32位随机字符串
    """
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    rand = random.Random()
    return "".join([chars[rand.randint(0, len(chars) - 1)] for i in range(32)])


def decrypt(api_key, nonce, ciphertext, associated_data):
    """
    证书和回调报文解密
    :param api_key: API v3秘钥
    :param nonce: 加密使用的随机串初始化向量
    :param ciphertext: ase64编码后的密文
    :param associated_data: 附加数据包（可能为空）
    :return: 解密后的数据
    """
    key_bytes = api_key.encode()
    nonce_bytes = nonce.encode()
    ad_bytes = associated_data.encode()
    data = b64decode(ciphertext)
    aesgcm = AESGCM(key_bytes)
    return aesgcm.decrypt(nonce_bytes, data, ad_bytes).decode('utf-8')
